package com.ly.mpayment.persist.service.upshopinfo;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.ly.mpayment.core.util.JsonUtils;
import com.ly.mpayment.core.util.ResultMessage;
import com.ly.mpayment.persist.catstorage.Result;
import com.ly.mpayment.rest.recharge.AutoOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.DateUtils;
import com.ly.mpayment.persist.entity.PlatFormAccount;
import com.ly.mpayment.persist.entity.PlatFormAccountRecord;
import com.ly.mpayment.persist.entity.UpRechargeRecord;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.entity.User;
import com.ly.mpayment.persist.hibernate.Page;
import com.ly.mpayment.persist.service.AbstractService;
import com.ly.mpayment.persist.service.platformaccount.IPlatformAccountService;
import com.ly.mpayment.persist.service.platformaccountrecord.IPlatFormAccountRecordService;
import com.ly.mpayment.persist.service.uprechargerecord.IUpRechargeRecordService;
import com.ly.mpayment.persist.service.user.IUserService;

import net.sf.json.JSONObject;
import org.springframework.util.CollectionUtils;

@Service
public class UpShopInfoServiceImpl extends AbstractService<UpShopInfo, Serializable> implements IUpShopInfoService{

	@Autowired
	IUserService userService;

	@Autowired
	IPlatformAccountService accountService;

	@Autowired
	IUpRechargeRecordService upRechargeService;

	@Autowired
	IPlatFormAccountRecordService recordService;

	@Override
	public boolean addUpshopinfo(UpShopInfo upshop) {
		if(upshop != null){
			this.saveOrUpdate(upshop);
			return true;
		}
		return false;
	}

	@Override
	public boolean updateUpshopinfo(UpShopInfo upshop) {
		if(upshop != null){
			this.saveOrUpdate(upshop);
			return true;
		}
		return false;
	}

	@Override
	public String updateUpSwitch(JSONObject json) {
		UpShopInfo shopInfo = this.findById(json.getString("upshopuuid"));
		if(shopInfo == null){
			return ResultMessage.getFailt("不存在");
		}
		shopInfo.setNoticeSwitch(json.getBoolean("noticeSwitch"));
		if(this.updateEntity(shopInfo) != null){
			return ResultMessage.getSucceed(null);
		}
		return ResultMessage.getFailt("");
	}


	@Override
	public UpShopInfo findById(String id) {
		return this.findUnique("select u from UpShopInfo u left join fetch u.user left join fetch u.provincialInformation where u.status = 1 and u.upshopuuid = ?", id);
	}

	@Override
	public Page<UpShopInfo> findPageUpshopinfo(Map<String, Object> parameters, int start, int pageSize) {
		return this.findPageByNamed("select u from UpShopInfo u left join fetch u.user uu where u.status = 1  and  uu.usertype = 4 #[ and uu.username like :shopName]#  #[ and u.shopnum = :phonenum]# #[ and uu.userstatus = :userstatus]# order by uu.username ", parameters, start, pageSize);
	}

	@Override
	public boolean addUpshopinfo(UpShopInfo shop, User user) {
		if(shop != null && user != null){
			user = userService.addUserShop(user);
			shop.setUser(user);
			this.saveOrUpdate(shop);
			return true;
		}
		return false;
	}

	@Override
	public UpShopInfo findShopNum(String shopNum) {
		return this.findUnique("select u from UpShopInfo u where u.shopnum = ?", shopNum);
	}

	@Override
	public UpShopInfo findShopIp(String shopIp) {
		return this.findUnique("select u from UpShopInfo u where u.upshopip = ?", shopIp);
	}

	@Override
	public  boolean updateShopAmount(UpShopInfo shop, User adminUser, BigDecimal bigDecimal,String remark,int paytype) {
		if(shop != null){
			shop = this.findById(shop.getUpshopuuid());
			UpRechargeRecord recharge = new UpRechargeRecord();
			PlatFormAccount account = accountService.findByAccount();
			if(account != null){
				if(paytype == Config.RECHARGE[0]){
					//充值
					shop.setUpshopbalance(shop.getUpshopbalance().add(bigDecimal));
					account.setPlatformamount(account.getPlatformamount().subtract(bigDecimal));
					shop.setTotalMoney(shop.getTotalMoney().add(bigDecimal));
				}else{
					//扣款
					shop.setUpshopbalance(shop.getUpshopbalance().subtract(bigDecimal));
					account.setPlatformamount(account.getPlatformamount().add(bigDecimal));
					shop.setTotalMoney(shop.getTotalMoney().subtract(bigDecimal));
				}
				this.updateEntity(shop);
				accountService.updatePlatformaccount(account);
				recharge.setPlatFormAccount(account);
			}else{
				//如果为null 则初始化一条
				account = accountService.addPlatformaccount();
				if(paytype == Config.RECHARGE[0]){
					shop.setUpshopbalance(shop.getUpshopbalance().add(bigDecimal));
					account.setPlatformamount(account.getPlatformamount().subtract(bigDecimal));
				}else{
					shop.setUpshopbalance(shop.getUpshopbalance().subtract(bigDecimal));
					account.setPlatformamount(account.getPlatformamount().add(bigDecimal));
				}
				this.updateEntity(shop);
				accountService.updatePlatformaccount(account);
				recharge.setPlatFormAccount(account);
			}


			//系统账户 针对上游 充值 是扣款 ，扣款 是加款
			PlatFormAccountRecord record = new PlatFormAccountRecord();
			record.setChangeamount(paytype == Config.RECHARGE[1] ? bigDecimal : bigDecimal.multiply(new BigDecimal(-1)) );
			record.setChangetime(DateUtils.getNowDate());
			record.setPlatFormAccount(account);
			record.setRemark(paytype == 1 ? Config.rechargeUp[1] :  Config.rechargeUp[0] );
			record.setUser(adminUser);
			record.setPayType(paytype == 1 ? 2 : 1);
			recordService.addPlatformaccountrecord(record);

			recharge.setUser(shop.getUser());
			recharge.setRechargetime(DateUtils.getNowDate());
			recharge.setRechargestatus(Config.publicStatus[1]);
			recharge.setRemark(remark);
			recharge.setRechargeamount(paytype == Config.RECHARGE[0] ? bigDecimal : bigDecimal.multiply(new BigDecimal(-1)));
			recharge.setPayType(paytype);
			recharge.setBalance(shop.getUpshopbalance());
			upRechargeService.addUprechargerecord(recharge);
			return true;
		}
		return false;
	}

	@Override
	public UpShopInfo findByUserId(String userId) {
		return this.findUnique("select u from UpShopInfo u left join fetch u.user where u.user.userstatus = 1 and u.user.useruuid = ?", userId);
	}

	@Override
	public List<UpShopInfo> findAllByProvince(String provinceuuid) {
		return this.find("select u from UpShopInfo u left join fetch u.user uu where uu.usertype = 4 and u.provincialInformation.provinceuuid = ? order by uu.username", provinceuuid);
	}

	@Override
	public List<UpShopInfo> findAllByProvince() {
		return this.find("select u from UpShopInfo u left join fetch u.user uu where uu.usertype = 4 order by uu.username");
	}


	/**
	 * "upshopuuid","pressOrder"
	 * @param json
	 * @return
	 */
	@Override
	public String updatePressOrder(JSONObject json) {
		UpShopInfo shopInfo = this.findById(json.getString("upshopuuid"));
		if(shopInfo == null){
			return ResultMessage.getFailt("不存在");
		}
		shopInfo.setPressOrder(json.getBoolean("pressOrder"));
		if(this.updateEntity(shopInfo) != null){
			return ResultMessage.getSucceed(null);
		}
		return ResultMessage.getFailt("");
	}

	/**
	 * "upshopuuid","artificial"
	 * @param json
	 * @return
	 */
	@Override
	public String updateArtificial(JSONObject json) {
		UpShopInfo shopInfo = this.findById(json.getString("upshopuuid"));
		if(shopInfo == null){
			return ResultMessage.getFailt("不存在");
		}
		shopInfo.setArtificial(json.getBoolean("artificial"));
		if(this.updateEntity(shopInfo) != null){
			return ResultMessage.getSucceed(null);
		}
		return ResultMessage.getFailt("");
	}

	@Override
	public String updateQuerySwitch(JSONObject json) {
		UpShopInfo shopInfo = this.findById(json.getString("upshopuuid"));
		if(shopInfo == null){
			return ResultMessage.getFailt("不存在");
		}
		shopInfo.setQuerySwitch(json.getBoolean("querySwitch"));
		if(this.updateEntity(shopInfo) != null){
			AutoOrderService.upOrders.clear();
			return ResultMessage.getSucceed(null);
		}
		return ResultMessage.getFailt("");
	}

	@Override
	public UpShopInfo findByAppId(String appid) {
		return this.findUnique("select u from UpShopInfo u left join fetch u.user where u.status = 1 and u.appId = ?", appid);
	}



	@Override
	public JSONObject findByBillUserId(String useruuid,String startTimes,String endtTimes) {

		String startTime = startTimes + " 00:00:00";
		String endTime = endtTimes  + " 23:59:59";

		String sql = " select " +
				" (SELECT count(fl.downorderuuid) FROM uporder fl where fl.useruuid = d.useruuid and fl.`status` = 2 and " +
				" fl.createtime >= '"+startTime+"' and" +
				" fl.createtime  <'"+endTime+"'   ) '订单数'," +
				" d.useruuid,u.username," +
				" (SELECT sum(fl.discount_amount) FROM uporder fl where fl.useruuid = d.useruuid and fl.`status` = 2 and " +
				" fl.createtime >= '"+startTime+"' and" +
				" fl.createtime  <'"+endTime+"'   ) 'xh'," +
				" (SELECT sum(fl.rechargeamount) FROM uporder fl where fl.useruuid = d.useruuid and fl.`status` = 2 and " +
				" fl.createtime >= '"+startTime+"' and" +
				" fl.createtime  <'"+endTime+"'   ) 'mz'," +
				" (SELECT IFNULL(sum(c.rechargeamount),0) from uprechargerecord c where c.useruuid = u.useruuid" +
				" and c.createtime >= '"+startTime+"' and c.createtime <= '"+endTime+"') 'jk'," +
				" (select f.upshopbalance from upshopinfo f where f.useruuid = u.useruuid)'ye'," +
				" (select IFNULL(f.balance,0) from zero_balance_up f where f.user_id = u.useruuid and f.create_time = '"+startTime+"')'sq'" +
				" from upshopinfo d " +
				" inner join user u on u.useruuid = d.useruuid" +
				" where    d.useruuid = '"+useruuid+"'" +
				" GROUP BY d.useruuid; ";
		JSONObject obj = JsonUtils.getJSONOBJCT();
		List lists = this.getSession().createSQLQuery(sql).list();
		if(!CollectionUtils.isEmpty(lists)){
			for (int i = 0; i < lists.size(); i++) {
				Object[] objs = (Object[]) lists.get(i);
				obj.put("orderNum", objs[0] == null ? "" : objs[0].toString());
				obj.put("username", objs[2] == null ? "" : objs[2].toString());
				obj.put("xh", objs[3] == null ? "" : objs[3].toString());
				obj.put("mz", objs[4] == null ? "" : objs[4].toString());
				obj.put("jkje", objs[5] == null ? "" : objs[5].toString());
				obj.put("dqye", objs[6] == null ? "" : objs[6].toString());
				obj.put("sqye", objs[7] == null ? "" : objs[7].toString());
			}
		}
		return obj;
	}
}
